﻿using System;
using System.Net;
using System.Web;

namespace NGM.MicrosoftConnect {
    public class MicrosoftConnectWebRequestBuilder {
        private readonly string _accessToken;
        private readonly string _url;
        private string _webRequestMethod = WebRequestMethods.Http.Get;
        private string _contentType;

        public MicrosoftConnectWebRequestBuilder(string url) {
            _url = url;
        }

        public MicrosoftConnectWebRequestBuilder(string accessToken, string url) : this(url) {
            _accessToken = accessToken;
        }

        public MicrosoftConnectWebRequestBuilder WithContentType(string contentType) {
            _contentType = contentType;
            return this;
        }

        public MicrosoftConnectWebRequestBuilder WithWebRequestType(string webRequestType) {
            _webRequestMethod = webRequestType;
            return this;
        }

        public HttpWebRequest Build() {
            var uriBuilder = new UriBuilder(MicrosoftConnectConstants.LiveQueryPointer);
            
            AppendPathPart(uriBuilder, _url);
            AppendQueryParameter(uriBuilder, "access_token", _accessToken);

            var request = (HttpWebRequest)WebRequest.Create(uriBuilder.Uri);
            request.Method = _webRequestMethod;

            if (!string.IsNullOrEmpty(_contentType))
                request.ContentType = _contentType;

            return request;
        }

        private static void AppendPathPart(UriBuilder uriBuilder, string pathPart) {
            if (string.IsNullOrEmpty(pathPart))
                return;

            if (uriBuilder.Path.EndsWith("/"))
                uriBuilder.Path += string.Concat(pathPart, "/");
            else
                uriBuilder.Path += string.Concat("/", pathPart, "/");
        }

        private static void AppendQueryParameter(UriBuilder uriBuilder, string paramName, string paramValue) {
            if (string.IsNullOrEmpty(paramValue))
                return;

            if (uriBuilder.Path.EndsWith("/"))
                uriBuilder.Path = uriBuilder.Path.TrimEnd('/');

            if (uriBuilder.Query != null && uriBuilder.Query.Length > 1)
                uriBuilder.Query = uriBuilder.Query.Substring(1) + "&" + paramName + "=" + HttpUtility.UrlEncode(paramValue);
            else
                uriBuilder.Query = paramName + "=" + HttpUtility.UrlEncode(paramValue);
        }
    }
}